package com.system.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.base.persistence.Page;
import com.common.base.utils.MD5Encode;
import com.common.web.controller.BaseController;
import com.common.web.resp.vo.ResponseInfo;
import com.system.service.ISysStaffService;
import com.system.vo.SysRoleVO;
import com.system.vo.SysStaffVO;


@Controller
@RequestMapping("/sys/staffMgr")
public class SysStaffController extends BaseController{

	@Autowired
	private ISysStaffService staffService;

    
	@RequestMapping
	public String index(){
		return "view-system/staff/staffInfo";
	}
	
	/**
	 * 根据机构查询员工列表
	 * @param page,sysOrgVO
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="staffList",method=RequestMethod.POST,produces="application/json; charset=utf-8")
	@ResponseBody
	public String staffList(Page<SysStaffVO> page, SysStaffVO sysStaffVO) throws Exception{
		return null;
	}

	@RequestMapping("queryStaffDetail/{staff_id}")
	@ResponseBody
	public String queryStaffDetail(@PathVariable("staff_id") String staff_id){
		SysStaffVO vo = staffService.queryStaffDetail(staff_id);
		return toJSONString(vo);
	}
	
	@RequestMapping("otherInfo/{staffId}")
	public String queryStaffOtherInfoIndex(@PathVariable("staffId") String staffId, HttpServletRequest request) {
		request.setAttribute("staffId", staffId);
		return "view-system/platform/inner-staff/staffOtherInfo";
	}
	
	/*多条件查询员工的信息
	 */
	@RequestMapping("queryLst")
	@ResponseBody
	public String query(Page<SysStaffVO> page, SysStaffVO staff, String[] orgIds,
                        String roleName, HttpServletRequest request){
		try {
			List<String> ids = Arrays.asList(orgIds);
			Map<Object, Object>map=new HashMap<Object, Object>();
			map.put("staffId", staff.getStaffId());
			map.put("roleName", roleName);
			map.put("staffName", staff.getStaffName());
		    map.put("state", staff.getState());
			map.put("orgIds", ids);
		    List<SysStaffVO> list=staffService.findStaffSBymap(map, page);
		    ResponseInfo info = new ResponseInfo(page,list);
		    String json=info.toJson();
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseInfo.errorJson("系统异常");
		}
		
	}
	
	/* 修改员工的基本信息，和对应的角色关系
	 * 
	 */
	@RequestMapping("editStaffInfoAndRoles")
	@ResponseBody
	public String editStaffInfoAndRoles(SysStaffVO staff, String[] roleIds){
		ResponseInfo info = new ResponseInfo();
		try {
			staffService.editStaffInfoAndRoles(staff,roleIds);
		} catch (Exception e) {
			info.setSuccess(false);
			info.setMessage("修改失败");
			e.printStackTrace();
		}
		return info.toJson();
	}
	@RequestMapping("findRolesByUserId")
	@ResponseBody
	public String findRolesByUserId(String staffId){
		try {
			List<SysRoleVO> sysRoleVOs=staffService.findRolesByUserId(staffId);
		    ResponseInfo info = new ResponseInfo();
		    info.setInfo(sysRoleVOs);
			return info.toJson();
		} catch (Exception e) {
			return ResponseInfo.errorJson("系统异常");
		}
	}
	

	@RequestMapping(value = "/addStaff",method=RequestMethod.POST,produces="application/json; charset=utf-8")
	@ResponseBody
	public String addStaff(SysStaffVO staff){
		ResponseInfo ri = new ResponseInfo();
		Subject subject= SecurityUtils.getSubject();
		Session session=subject.getSession();
		SysStaffVO currentStaff = (SysStaffVO) session.getAttribute("user");

		//查询员工编号是否重复
		int staffCount= 0 ;
		try{
			staffCount = staffService.countStaffById(staff.getStaffId());
		}catch (Exception ecxeption){
			ecxeption.printStackTrace();
		}

		if(staffCount!=0){
			ri.setMessage("添加失败 !用户编号重复请再试一次.");
			ri.setSuccess(false);
			return ri.toJson();
		}

		//对用户密码进行加密
		staff.setStaffPsw(MD5Encode.encode(staff.getStaffPsw()));
		//设置添加人的编号
		staff.setInsertId(currentStaff.getStaffId());
		//设置添加时间
		staff.setStaffCreateTime(new Date());
		try {
			staffService.addStaff(staff);
		}catch (Exception e){
			e.printStackTrace();
			ri.setMessage("员工添加失败");
			ri.setSuccess(false);
		}
		ri.setMessage("员工添加成功");
		ri.setSuccess(true);
		return ri.toJson();
	}

	@RequestMapping("/delStaff")
	@ResponseBody
	public String deleteStaff(String staffId){
		ResponseInfo ri = new ResponseInfo();
		SysStaffVO currStaff = (SysStaffVO) SecurityUtils.getSubject().getSession().getAttribute("user");
		if(StringUtils.isNotBlank(staffId) && !currStaff.getStaffId().equals(staffId)){
			if(staffService.deleteStaff(staffId)){
				if(staffService.deleteStaffRoles(staffId)){
					ri.setMessage("删除成功！");
				}else {
					ri.setMessage("删除失败！");
				}
			}
		}else {
			ri.setSuccess(false);
			ri.setMessage("非法操作，删除失败！");
		}
		return ri.toJson();
	}

	@RequestMapping(value = "/updateStaff",method=RequestMethod.POST,produces="application/json; charset=utf-8")
	@ResponseBody
	public String updateStaff(SysStaffVO staff){
		ResponseInfo ri = new ResponseInfo();
		// 若需添加操作人信息，此处获取当前 操作人信息
		//Subject subject= SecurityUtils.getSubject();
		//Session session=subject.getSession();
		//SysStaffVO currentStaff = (SysStaffVO) session.getAttribute("user");
		//如果密码不为空对密码进行加密
		if(StringUtils.isNotBlank(staff.getStaffPsw())){
			staff.setStaffPsw(MD5Encode.encode(staff.getStaffPsw()));
		}
		boolean flag = staffService.updateStaff(staff);
		if (flag){
			ri.setMessage("更新成功");
		}else {
			ri.setMessage("更新失败");
			ri.setSuccess(false);
		}
		return ri.toJson();
	}
	
	@RequestMapping("/add/Index")
	public String addStaffIndex(){
		return "view-system/staff/staffAdd";
	}
	
	@RequestMapping("/choose/Index")
	public String chooseIndex(){
		return "view-system/staff/staffChoose";
	}
	
	@RequestMapping("/update/{staffId}/Index")
	public String updateCodeTypeIndex(@PathVariable("staffId") String staffId,HttpServletRequest request){
		SysStaffVO sysStaffVO = staffService.queryStaffOne(staffId);
		request.setAttribute("sysStaffVO", sysStaffVO);
		return "view-system/staff/staffUpdate";
	}
	
	@RequestMapping("/find/{staffId}/Roles")
	public String findRolesById(@PathVariable("staffId") String staffId,HttpServletRequest request){
		SysStaffVO sysStaffVO = staffService.queryStaffOne(staffId);
		request.setAttribute("sysStaffVO", sysStaffVO);
		return "view-system/staff/staffBaseInfo";
	}
}
